import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES, VALIDATION_ERROR_CODES } from '../../utils/errorCodes';
import { deleteFile } from '../../middleware/upload';

/**
 * 文件级注释：楼层管理控制器，提供楼层的增删改查与启用禁用
 */
export class FloorController extends BaseController {
  /**
   * 获取楼层列表
   */
  async list(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, venueId, keyword } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      const where: any = {};
      if (venueId) where.venueId = parseInt(venueId as string);
      if (keyword) {
        where.OR = [
          { name: { contains: keyword as string } },
          { description: { contains: keyword as string } },
        ];
      }

      const [items, total] = await Promise.all([
        prisma.floor.findMany({ 
          where, 
          skip, 
          take: limitNum, 
          orderBy: { id: 'desc' },
          include: {
            venue: {
              select: {
                id: true,
                name: true,
                city: true,
                country: true
              }
            }
          }
        }),
        prisma.floor.count({ where }),
      ]);

      ResponseUtils.paginated(res, items, total, pageNum, limitNum, '获取楼层列表成功');
    } catch (error) { next(error); }
  }

  /** 获取楼层详情 */
  async detail(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      const item = await prisma.floor.findUnique({ 
        where: { id },
        include: {
          venue: {
            select: {
              id: true,
              name: true,
              city: true,
              country: true
            }
          }
        }
      });
      if (!item) return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '楼层不存在');
      ResponseUtils.success(res, item, '获取楼层详情成功');
    } catch (error) { next(error); }
  }

  /** 创建楼层 */
  async create(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { venueId, name, level, description, status } = req.body;
      if (!venueId || !name) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, 'venueId与name必填');
      
      // 验证场馆是否存在
      const venue = await prisma.venue.findUnique({ where: { id: parseInt(venueId) } });
      if (!venue) return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '场馆不存在');
      
      // 处理平面图URL
      let floorPlanUrl = null;
      if (req.file) {
        floorPlanUrl = `/uploads/floor-plans/${req.file.filename}`;
      }
      
      const created = await prisma.floor.create({ 
        data: { 
          venueId: parseInt(venueId), 
          name, 
          level: level ? Number(level) : null, 
          description, 
          floorPlanUrl,
          status 
        } 
      });
      ResponseUtils.success(res, created, '创建楼层成功');
    } catch (error) { next(error); }
  }

  /** 更新楼层 */
  async update(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      
      // 获取当前楼层信息，用于删除旧平面图
      const currentFloor = await prisma.floor.findUnique({ where: { id } });
      if (!currentFloor) {
        return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '楼层不存在');
      }
      
      const { venueId, name, level, description, status } = req.body;
      
      // 如果更新了场馆，验证新场馆是否存在
      if (venueId && venueId !== currentFloor.venueId) {
        const venue = await prisma.venue.findUnique({ where: { id: parseInt(venueId) } });
        if (!venue) return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '场馆不存在');
      }
      
      // 处理平面图URL
      let floorPlanUrl = currentFloor.floorPlanUrl;
      if (req.file) {
        // 如果有新文件上传，删除旧文件
        if (currentFloor.floorPlanUrl) {
          const oldFilename = currentFloor.floorPlanUrl.split('/').pop();
          if (oldFilename) {
            deleteFile(oldFilename, 'floorPlan');
          }
        }
        floorPlanUrl = `/uploads/floor-plans/${req.file.filename}`;
      }
      
      const updateData: any = { 
        name, 
        level: level !== undefined ? Number(level) : null, 
        description, 
        floorPlanUrl,
        status 
      };
      
      // 只有在提供了venueId时才更新场馆
      if (venueId) {
        updateData.venueId = parseInt(venueId);
      }
      
      const updated = await prisma.floor.update({
        where: { id },
        data: updateData,
      });
      ResponseUtils.success(res, updated, '更新楼层成功');
    } catch (error) { next(error); }
  }

  /** 删除楼层 */
  async remove(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      
      // 获取楼层信息，用于删除平面图文件
      const floor = await prisma.floor.findUnique({ where: { id } });
      if (!floor) {
        return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '楼层不存在');
      }
      
      // 删除平面图文件
      if (floor.floorPlanUrl) {
        const filename = floor.floorPlanUrl.split('/').pop();
        if (filename) {
          deleteFile(filename, 'floorPlan');
        }
      }
      
      await prisma.floor.delete({ where: { id } });
      ResponseUtils.success(res, null, '删除楼层成功');
    } catch (error) { next(error); }
  }

  /** 启用楼层 */
  async enable(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      const updated = await prisma.floor.update({ where: { id }, data: { status: 'ACTIVE' } });
      ResponseUtils.success(res, updated, '楼层已启用');
    } catch (error) { next(error); }
  }

  /** 禁用楼层 */
  async disable(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      const updated = await prisma.floor.update({ where: { id }, data: { status: 'INACTIVE' } });
      ResponseUtils.success(res, updated, '楼层已禁用');
    } catch (error) { next(error); }
  }

  /** 上传楼层平面图 */
  async uploadFloorPlan(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      
      if (!req.file) {
        return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '请选择要上传的平面图文件');
      }
      
      // 获取当前楼层信息，用于删除旧平面图
      const currentFloor = await prisma.floor.findUnique({ where: { id } });
      if (!currentFloor) {
        return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '楼层不存在');
      }
      
      // 删除旧平面图文件
      if (currentFloor.floorPlanUrl) {
        const oldFilename = currentFloor.floorPlanUrl.split('/').pop();
        if (oldFilename) {
          deleteFile(oldFilename, 'floorPlan');
        }
      }
      
      // 更新平面图URL
      const floorPlanUrl = `/uploads/floor-plans/${req.file.filename}`;
      const updated = await prisma.floor.update({
        where: { id },
        data: { floorPlanUrl }
      });
      
      ResponseUtils.success(res, updated, '楼层平面图上传成功');
    } catch (error) { next(error); }
  }

  /** 删除楼层平面图 */
  async deleteFloorPlan(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const id = parseInt(req.params.id);
      if (isNaN(id)) return ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的ID');
      
      // 获取当前楼层信息
      const currentFloor = await prisma.floor.findUnique({ where: { id } });
      if (!currentFloor) {
        return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '楼层不存在');
      }
      
      // 检查是否有平面图
      if (!currentFloor.floorPlanUrl) {
        return ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '楼层没有平面图');
      }
      
      // 删除平面图文件
      const filename = currentFloor.floorPlanUrl.split('/').pop();
      if (filename) {
        deleteFile(filename, 'floorPlan');
      }
      
      // 更新楼层，清空平面图URL
      const updated = await prisma.floor.update({
        where: { id },
        data: { floorPlanUrl: null }
      });
      
      ResponseUtils.success(res, updated, '楼层平面图删除成功');
    } catch (error) { next(error); }
  }
}


